// pages/tcppage/tcppage.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
      input_ip:"0.0.0.0",
      input_port: 8080,
      msg: "---",
      tcp: "",
  },

  msglog(tomsg){
    this.setData({
      msg : tomsg
    })
  },

  ConfirmIP(event){
    this.input_ip = event.detail.value;
    this.msglog(this.input_ip)
  },

  ConfirmPort(event){
    this.input_port = event.detail.value;
    this.msglog(this.input_port)
  },

  

  handleTcp() {
    this.tcp = wx.createTCPSocket()
    console.log("connectting")
    this.tcp.connect({
      address: this.input_ip,
      port: this.input_port
    })
    this.tcp.onConnect(() => {
      this.msglog("Connectting")
      this.msglog(this.input_ip + ':' + this.input_port + "已连接")
    })
    this.tcp.onMessage((message) => {
      let unit8Arr = new Uint8Array(message.message) ;
      let decodedString = decodeURIComponent(escape((String.fromCharCode.apply(null, unit8Arr))));
      console.log("onMessage")
      console.log(message)
      console.log(message.localInfo)
      this.msglog(decodedString)
    })
    this.tcp.onError((res) => {
      console.log(res)
      this.msglog(res.errMsg)
      this.tcp=""
    })

    // setTimeout(function () {
    //  // 3s后，关闭socket
    //   tcp.close(() => {
    //     console.log("close")
    //   })
    // }, 3000)
  },

  closetcp(){
    if(this.tcp != undefined){
      this.tcp.close();
      this.tcp=""
      this.msglog("已断开")
    }else{
      this.msglog("无连接")
    }
  },

  inputtext(event){
    this.msg = event.detail.value;
    this.msglog(this.msg)
  },

  sendTcpData(){
    if(this.tcp != undefined){
      this.tcp.write(this.msg);
    }else{
      this.msglog("请先建立tcp连接")
    }
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})